<?php
/**
 * Admin callbacks
 */
function schedule_list() {
	$header = array(
		t('Train'),
		t('From'),
		t('To'),
		t('Departure'),
		t('Arrival'),
		t('Duration'),
		t('Hard seat'),
		t('Soft seat'),
		t('Hard berth'),
		t('Soft berth'),
		array('data' => t('Operations'), 'colspan' => 2),
	);
	
	if (arg(3) == 'sapa') {
		$type = 'sapa';
		$typeId = SAPA_TRAINS;
		$destinations = _get_destination_array($typeId);
	} else {
		$type = 'tn';
		$typeId = THONG_NHAT;
		$destinations = _get_destination_array($typeId);
	}
	
	$query = db_select('train_schedules', 'tb1');
    $query->join('trains', 'tb2', 'tb1.trid = tb2.trid');
    $query->fields('tb2')->fields('tb1');
	$query->condition('tb2.type', $typeId);
	$es = $query->execute()->fetchAll();
	
	$rows = array();
	if ($es) {
		foreach ($es as $e) {
			$rows[] = array(
				check_plain($e->name),
				$destinations[$e->train_from],
				$destinations[$e->train_to],
				check_plain($e->departure),
				check_plain($e->arrival),
				check_plain($e->duration),
				$e->hard_seat ? check_plain($e->hard_seat) .'$' : 'N/A',
				$e->soft_seat ? check_plain($e->soft_seat) .'$' : 'N/A',
				$e->hard_berth ? check_plain($e->hard_berth) .'$' : 'N/A',
				$e->soft_berth ? check_plain($e->soft_berth) .'$' : 'N/A',
				l(t('Sửa'), 'admin/structure/train_manager/' . $type . '/edit/' . $e->tsid),
				l(t('Xóa'), 'admin/structure/train_manager/' . $type . '/delete/' . $e->tsid),
			);
		}
	}
	
	if (!$rows) {
	  $rows[] = array(array(
		'data' => t('Không có lịch trình nào'),
		'colspan' => 12,
	  ));
	}
	$build['send_form_table'] = array(
		'#theme' => 'table',
		'#header' => $header,
		'#rows' => $rows,
	);
	return $build;
	
}

function schedule_add_form($form, &$form_state, array $schedule = array()) {
	if (arg(3) == 'sapa') {
		$typeId = SAPA_TRAINS;
	} else if (arg(3) == 'tn') {
		$typeId = THONG_NHAT;
	} else {
		if (empty($form_state['values']['sapa_chirld'])) {
			return false;
		}
	}
	$schedule += array(
		'tsid' => NULL,
		'trid' => NULL,
		'sapa_chirld' => NULL,
		'name' => '',
		'type' => '',
		'train_from' => '',
		'train_to' => '',
		'departure' => '',
		'arrival' => '',
		'duration' => '',
		'hard_seat' => 0,
		'soft_seat' => 0,
		'hard_berth' => 0,
		'soft_berth' => 0,
	);
	
	$from = get_train_type($typeId);
	$to = $from;
	
	if ($typeId == SAPA_TRAINS || isset($form_state['values']['sapa_chirld'])) {
		$form['sapa_chirld'] = array(
			'#type'             => 'select',
			'#title'            => t('Chọn Hãng tàu'),
			'#options'          => _get_sapa_chirld(),
			'#required'         => TRUE,
			'#default_value'    => $schedule['sapa_chirld'],
			'#ajax' => array(
			  'event'=>'change',
			  'callback' =>'ajax_load_sapa_group',
			  'wrapper' => 'train-div',
				'effect' => 'fade',
			),
		);
		$form['wrapper'] = array(
			'#prefix' => '<div id="train-div">',
			'#suffix' => '</div>',
		);
	}
	
	$trains = array();
	if ($typeId == THONG_NHAT) {
		$trains = train_manager_dbget_trains_tn(THONG_NHAT);
	}
	
	if (isset($form_state['values']['sapa_chirld'])) {
		$trains = train_manager_dbget_trains_sapa($form_state['values']['sapa_chirld']);
    }
	$form['wrapper']['trid'] = array(
		'#type'             => 'select',
		'#title'            => t('Tên tàu'),
		'#options'          => $trains,
		'#default_value'    => $schedule['trid'],
		'#required'         => TRUE,
	);
  
	$form['from'] = array(
		'#type'             => 'select',
		'#title'            => t('From'),
		'#options'          => $from,
		'#required'         => TRUE,
		'#default_value'    => $schedule['train_from'],
	);
  
	$form['to'] = array(
		'#type'             => 'select',
		'#title'            => t('To'),
		'#options'          => $to,
		'#required'         => TRUE,
		'#default_value'    => $schedule['train_to'],
	);
  
	$form['departure'] = array(
		'#type'				=> 'textfield',
		'#title'			=> t('Departure Time'),
		'#default_value'	=> $schedule['departure'],
		'#required'			=> TRUE,
		'#description'		=> t("Example: 06:00 or 6:00"),
	);
  
	$form['arrival'] = array(
		'#type'				=> 'textfield',
		'#title'			=> t('Arrival time'),
		'#default_value'	=> $schedule['arrival'],
		'#required'			=> TRUE,
		'#description'		=> t("Example: 06:00 or 6:00"),
	);
	
	$form['duration'] = array(
		'#type'				=> 'textfield',
		'#title'			=> t('Duration'),
		'#default_value'	=> $schedule['duration'],
		'#required'			=> TRUE,
		'#description'		=> t("Example: 7hr 35min"),
	);
    
	$form['hard_seat'] = array(
		'#type'				=> 'textfield',
		'#title'			=> t('Hard seat'),
		'#default_value'	=> $schedule['hard_seat'],
		'#required'			=> TRUE,
		'#description'		=> t("Đơn vị: $"),
	);
    
	$form['soft_seat'] = array(
		'#type'				=> 'textfield',
		'#title'			=> t('Soft seat'),
		'#default_value'	=> $schedule['soft_seat'],
		'#required'			=> TRUE,
		'#description'		=> t("Đơn vị: $"),
	);
    
	$form['hard_berth'] = array(
		'#type'				=> 'textfield',
		'#title'			=> t('Hard berth'),
		'#default_value'	=> $schedule['hard_berth'],
		'#required'			=> TRUE,
		'#description'		=> t("Đơn vị: $"),
	);
    
	$form['soft_berth'] = array(
		'#type'				=> 'textfield',
		'#title'			=> t('Soft berth'),
		'#default_value'	=> $schedule['soft_berth'],
		'#required'			=> TRUE,
		'#description'		=> t("Đơn vị: $"),
	);
	
	$form['tsid'] = array(
		'#type'				=> 'hidden',
		'#value'			=> $schedule['tsid'],
	);
	
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type'				=> 'submit',
		'#value'			=> t('Save & continue'),
	);
  
	return $form;
}

function schedule_add_form_submit($form, &$form_state) {
  $schedule = array(
    'trid' => $form_state['values']['trid'],
    'train_from' => $form_state['values']['from'],
    'train_to' => $form_state['values']['to'],
    'departure' => $form_state['values']['departure'],
    'arrival' => $form_state['values']['arrival'],
    'duration' => $form_state['values']['duration'],
    'hard_seat' => $form_state['values']['hard_seat'],
    'soft_seat' => $form_state['values']['soft_seat'],
    'hard_berth' => $form_state['values']['hard_berth'],
    'soft_berth' => $form_state['values']['soft_berth'],
  );
  
	if (!$form_state['values']['tsid']) {
		drupal_write_record('train_schedules', $schedule);
		drupal_set_message(t('Dữ liệu đã được thêm. Hãy tiếp tục.'));
	} else {
		$schedule['tsid'] = $form_state['values']['tsid'];
		drupal_write_record('train_schedules', $schedule, 'tsid');
		drupal_set_message(t('Dữ liệu đã cập nhật thành công.'));
		$form_state['redirect'] = 'admin/structure/train_manager/'. arg(3);
	}
}

function trains_list() {	
	$type = arg(4);
	$es = train_list_dbget($type);
	
	$header = array(
		t('Loại tàu'),
		t('Tên'),
		array('data' => t('Operations'), 'colspan' => 2),
	);
	
	$rows = array();
	$sapaChirld = _get_sapa_chirld();
	if ($es) {
		foreach ($es as $e) {
			$rows[] = array(
				$e->sapa_chirld ? check_plain(_get_trains($e->type)) . '/'. check_plain($sapaChirld[$e->sapa_chirld]) : check_plain(_get_trains($e->type)),
				check_plain($e->name),
				l(t('Sửa'), 'admin/structure/train_manager/trains/'.$type.'/edit/' . $e->trid),
				l(t('Xóa'), 'admin/structure/train_manager/trains/'.$type.'/delete/' . $e->trid),
			);
		}
	}
	
	if (!$rows) {
	  $rows[] = array(array(
		'data' => t('Không có bản ghi nào'),
		'colspan' => 12,
	  ));
	}
	$build['send_form_table'] = array(
		'#theme' => 'table',
		'#header' => $header,
		'#rows' => $rows,
	);
	return $build;
	
}
function deckfifty_fox_ajax_callback($form, $form_state) {
  return $form['fox_wrapper'];
}
function trains_add($form, &$form_state, array $trains = array()) {
	$trains += array(
		'trid' => NULL,
		'name' => '',
		'type' => '',
		'sapa_chirld' => '',
	);
	
	$type = arg(4);
	
	$form['name'] = array(
		'#type'				=> 'textfield',
		'#title'			=> t('Tên'),
		'#default_value'	=> $trains['name'],
		'#required'			=> TRUE,
	);
	
	if ($type == SAPA_TRAINS) {
		$form['sapa_chirld'] = array(
			'#type'             => 'select',
			'#title'            => t('Loại tàu'),
			'#options'          => _get_sapa_chirld(),
			'#default_value'    => $trains['sapa_chirld'],
			'#required'         => TRUE
		);	
	}
	 
	$form['type'] = array(
		'#type'				=> 'hidden',
		'#value'			=> $type,
	);
	$form['trid'] = array(
		'#type'				=> 'hidden',
		'#value'			=> $trains['trid'],
	);
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type'				=> 'submit',
		'#value'			=> t('Save & continue'),
	);
	
	return $form;	
}

function trains_add_submit($form, &$form_state, array $values = array()) {
	if (empty($form_state['values']['trid'])) {
		drupal_write_record('trains', $form_state['values']);
		drupal_set_message(t('Dữ liệu: %title đã được thêm. Hãy tiếp tục.', array('%title' => $form_state['values']['name'])));
	} else {
		drupal_write_record('trains', $form_state['values'], array('trid'));
		drupal_set_message(t('Dữ liệu đã được cập nhật thành công.'));
		$form_state['redirect'] = 'admin/structure/train_manager/trains/'.arg(4);
	};
}

function trains_delete($form, &$form_state, array $trains) {
	$form['trains'] = array(
		'#type' => 'value',
		'#value' => $trains,
	);

	return confirm_form(
		$form,
		t('Are you sure you want to delete %title?', array('%title' => $trains['name'])),
		'admin/structure/train_manager/trains',
		t('This action cannot be undone.'),
		t('Delete'),
		t('Cancel')
	);
}

function trains_delete_submit($form, &$form_state) {
  $trains = $form['trains']['#value'];
  
  $query = db_delete('trains')
        ->condition('trid', $trains['trid'])
        ->execute();
  
  $query = db_delete('train_schedules')
        ->condition('trid', $trains['trid'])
        ->execute();

  drupal_set_message(t('Name %title has been deleted.', array('%title' => $trains['name'])));
  watchdog('events', 'Name %title has been deleted.', array('%title' => $trains['name']), WATCHDOG_NOTICE);

  $form_state['redirect'] = 'admin/structure/train_manager/trains/'.arg(4);
}

function ticket_delete($form, &$form_state, array $schedules) {
	$form['schedule'] = array(
		'#type' => 'value',
		'#value' => $schedules,
	);

	return confirm_form(
		$form,
		t('Are you sure you want to delete this ticket?'),
		'admin/structure/train_manager/'. arg(3),
		t('This action cannot be undone.'),
		t('Delete'),
		t('Cancel')
	);
}

function ticket_delete_submit($form, &$form_state) {
  $schedule = $form['schedule']['#value'];
  
  $query = db_delete('train_schedules')
        ->condition('tsid', $schedule['tsid'])
        ->execute();

  drupal_set_message(t('Ticket %title has been deleted.', array('%title' => $schedule['train_from'] .'-'.$schedule['train_to'])));

  $form_state['redirect'] = 'admin/structure/train_manager/'. arg(3);
}

function ajax_load_sapa_group($form, $form_state) {
	return $form['wrapper'];
}

function train_list_dbget($id) {
	$query = db_select('trains', 'tb1');
    $query->fields('tb1')->condition('tb1.type', $id);
	return $query->execute()->fetchAll();
}

function get_train_type($type = THONG_NHAT) {
	if ($type == SAPA_TRAINS) {
		return _get_destination_array($type);
	} else {
		return  _get_destination_array($type);
	}
}
